package leetcode.editor.cn.q1_300.q150;

import leetcode.editor.cn.util.list.singly.ListNode;

/**
 * @author qidi
 * @date 2022-01-21 15:13:48
 */
class Q0160_IntersectionOfTwoLinkedLists {

    //leetcode submit region begin(Prohibit modification and deletion)
    public class Solution {
        public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
            int aSize = 0;
            ListNode aCur = headA;
            while (aCur != null) {
                aCur = aCur.next;
                aSize++;
            }

            int bSize = 0;
            ListNode bCur = headB;
            while (bCur != null) {
                bCur = bCur.next;
                bSize++;
            }

            aCur = headA;
            bCur = headB;
            if (aSize > bSize) {
                int step = aSize - bSize;
                while (step != 0 || aCur != null) {
                    if (step > 0) {
                        step--;
                        aCur = aCur.next;
                    } else {
                        if (aCur == bCur) {
                            return aCur;
                        }
                        aCur = aCur.next;
                        bCur = bCur.next;
                    }
                }
            } else {
                int step = bSize - aSize;
                while (step != 0 || aCur != null) {
                    if (step > 0) {
                        step--;
                        bCur = bCur.next;
                    } else {
                        if (aCur == bCur) {
                            return aCur;
                        }
                        aCur = aCur.next;
                        bCur = bCur.next;
                    }
                }
            }
            return null;
        }
    }
    //leetcode submit region end(Prohibit modification and deletion)


    public static void main(String[] args) {
        Solution solution = new Q0160_IntersectionOfTwoLinkedLists().new Solution();
    }
}